//
//  HRMainTabBarViewController.swift
//  微博
//
//  Created by 众力金融 on 2017/1/5.
//  Copyright © 2017年 众力金融. All rights reserved.
//

import UIKit
import SVProgressHUD

class HRMainTabBarViewController: UITabBarController {
 
    //定时器
    fileprivate var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
     setupChildControllers()
     setupComposButton()
     setupTimer()
        //设置新特性
     setupNewfeatureView()
     //设置代理
        delegate = self
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userlogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
        
    }
    deinit {
        //销毁定时器
        timer?.invalidate()
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    /**
     portrait: 竖屏
     landscape: 横屏
     
     - 使用代码控制横竖屏 以后别界面需要横屏 单独处理
     - 设置支持的方向之后 当前的控制器级子控制器都会遵守这个方向
     - 如果 视频播放 通常是通过 modal 转场展现
    */
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    //MARK: - 监听方法
    @objc fileprivate func userlogin(n: Notification) {
        
        var deadline = DispatchTime.now()
        print("用户登录通知\(n)")
        //判断 n.obj 是否有值 如果有值 提示用户登录
        if n.object != nil {
            
            SVProgressHUD.setDefaultStyle(.light)
            SVProgressHUD.showInfo(withStatus: "用户登录超时,需要重新登录")
            deadline = DispatchTime.now()
           
        }
        DispatchQueue.main.asyncAfter(deadline: deadline) {
            SVProgressHUD.setDefaultStyle(.custom)
            //展现登录控制器
            let nav = UINavigationController(rootViewController: HROAuthViewController())
            self.present(nav, animated: true, completion: nil)
        }
        
       
    }
    //FIME: 没有实现
    //@objc 允许这个函数在运行时 通过 oc的消息机制 访问
  @objc fileprivate  func composeStatus() {
        print("写微博")
    
//    // 测试方向的旋转
//    let vc = UIViewController()
//    vc.view.backgroundColor = UIColor.cz_random()
//    let nav = UINavigationController(rootViewController: vc)
//    present(nav, animated: true, completion: nil)
    
    }
    
    //MARK: -私有控件
   fileprivate lazy var composButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")

}
//MARK: - 新特性视图欢迎和引导页
extension HRMainTabBarViewController {
    fileprivate func setupNewfeatureView() {
        
        // 判断是否denglu
        if !HRNetworkManager.shared.userlogon {
            return
        }
    //2.如果更新显示新特性 否则显示欢迎
        let v = isNewVierssion ? HRNewFeatureView.FeatureView() : HRWelcomeView.welcome()
        
    //3.添加视图
        v.frame = view.bounds
        view.addSubview(v)
    }
    //extension 中可以有计算型属性 不会占用存储空间
    //构造函数给属性分配空间
    fileprivate var isNewVierssion: Bool {
//        //1.当前的版本号 CFBundleShortVersionString
//        print("23asd \(Bundle.main.infoDictionary)")
//        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
//        //2.取保存 Document(iTunes)(最好偏好设置)目录中的之前的版本号
//        UserDefaults.standard.set(currentVersion, forKey: "currentVersion")
//        
//        //3.将当前版本号保存在沙盒
//        
//        //4.返回两个版本是否一致 yes no new
        var isfirstLaunch: Bool
        if UserDefaults.standard.value(forKey: "firstLaunch") == nil {
            UserDefaults.standard.set(true, forKey: "firstLaunch")
            isfirstLaunch = true
        }else {
            isfirstLaunch = false
        }
        return isfirstLaunch
    }
}

//MARK: - UITabBarControllerDelegate
extension HRMainTabBarViewController: UITabBarControllerDelegate {
    
    /// 将要选择tabbarItem
    ///
    /// - Parameters:
    ///   - tabBarController: TabBarController
    ///   - viewController: 目标控制器
    /// - Returns: 是否切换目标的控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
      
        print("将要切换到 \(viewController)")
        //获取控制器在数组的索引
      let index = (childViewControllers as NSArray).index(of: viewController)
        
        //判断当前索引是首页 同时index也是首页 重复点击首页的按钮
        if selectedIndex == 0 && selectedIndex == index {
            print("点击首页")
            //让表格滚到顶部
            //-获取到控制器
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! HRHomeViewController
            vc.tableview?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            //刷新数据
           DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
             vc.loadData()
           })
            //清除badgeNumber
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
            
        }
        //判断目标控制是否是 UIViewController
        return !viewController.isMember(of: UIViewController.self)
    }
    
}

//MARK: - 定时器的相关方法
extension HRMainTabBarViewController {
    //定义定时器
    fileprivate func setupTimer() {
        
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector:#selector(updateTimer) , userInfo: nil, repeats: true)
    }
    
    @objc fileprivate func updateTimer() {
        
        if !HRNetworkManager.shared.userlogon {
            return
        }
        
        HRNetworkManager.shared.unreadCount { (count) in
            
            print("检测到 \(count) 条微博")
            //设置首页 tabbarItem 的badgeNumber 从ios8.0 要用户授权才可以
            self.tabBar.items?[0].badgeValue =  count > 0 ? "\(count)" : nil
            
            //设置 app 的 badgetNumber
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

// extension 类似于OC中的 分类 在Swift 中可以用来区分代码块
// 可以把相近的功能的函数 放在一个extensoin中 便于代码的维护
// 注意 和oc的分类一样 extension 中不能定义属性
extension HRMainTabBarViewController {
    
    
  fileprivate func setupComposButton() {
        
        tabBar.addSubview(composButton)
    //计算按钮的高度
    let count = CGFloat(childViewControllers.count)
    //将向内缩进宽度 能够让按钮的宽度变大 盖住容错点 防止传帮
    let width = tabBar.bounds.width / count
    
    //CGRextInset 正数是向内缩进 负数向外扩展
    composButton.frame = tabBar.bounds.insetBy(dx: 2 * width, dy: 0)
    
    composButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    
    
    }
    
    
    
  fileprivate func setupChildControllers() {
    
    
    //获取沙盒json路径
    let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let jsonpath = (docDir as NSString).appendingPathComponent("demo.json")
    
    var data = NSData(contentsOfFile: jsonpath)
    
    print("~~data~\(data)")
    //判断data是否有文件 如果没有文件 说明沙盒没有文件
    if data == nil {
        //从Bundle加载data
        let path = Bundle.main.path(forResource: "main.json", ofType: nil)
        data = NSData(contentsOfFile: path!)
    }
    
    //data一定会有值 反序列化
//    //从bundle加载配置控制器
    // throw 抛出异常
    // try? 如果解析成功 就有值 否则 为nil
    // 方法二 try! 如果解析成功就有值 否则为nil
    /** 处理异常 do {
     let array = try? JSONSerialization.jsonObject(with: data! as Data, options: .allowFragments)
    }catch {
      print(error)
     }
    */
    // oc中有 try catch 
    // 如果 try catch  一旦不平衡 就会出现内存泄露
    
    guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]]
        else {
           
            return
    }
    
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict as [String : AnyObject]))
        }
        
        viewControllers = arrayM
      print("~~~~\(arrayM)")
        
    }
   
    
    /// 使用字典创建一个子控制器
    ///
    /// - Parameter dict: 信息字典
    /// - Returns: 字控制器
    private func controller(dict: [String: AnyObject]) -> UIViewController {
        
        //1.去的字典内容
       guard let clsName = dict["clsName"] as? String,
        let title = dict["title"] as? String,
        let imageName = dict["imageName"] as? String,
        let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? HRBaseViewController.Type,
        let visitorDic = dict["visitorInfo"] as? [String: String]
        else {
            
            return UIViewController()
        }
        
        //2.创建视图控制器
        // - 讲clsName 转换成 cls
        let vc = cls.init()
        vc.title = title
        
        vc.visitorInfoDictionary = visitorDic
        
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_highlighted")?.withRenderingMode(.alwaysOriginal)
        //设置tabbar 标题颜色
        //vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .highlighted)
        //系统默认的是12字体
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12)], for: .normal)
        let nav = HRNavigationController(rootViewController: vc)
        
        return nav
    }
}
